﻿//console.clear();
function ShouldRenderHeroButton(renderCtx) {
    return true;
}

var CIBResources = {
    'ru-ru': {
        CalloutText: 'Создайте новый элемент'
    },
    CalloutText: 'Create a new item'
};

var NewItemCalloutData = function (params) {
    var InParams = params || {};
    var listId;
    var CTList = [];
    var _self = this;
    var RootFolderCTId = "0x012001";

    function _init() {
        var CustomEvent = {};
        CustomEvent.OnPreRender = function (ctx) {
            AddStyles();
        };

        CustomEvent.OnPostRender = function (ctx) {

            var wpq = ctx.wpq;

            var Hero = document.getElementById('Hero-' + wpq);

            if (Hero) {
                if (InParams.ReloadPage || InParams.Mask) {
                    _self.Mask(ctx, Hero);
                }

                Hero.setAttribute('class', 'display-none');


                _self.listId = ctx.listName;
                SP.SOD.executeOrDelayUntilScriptLoaded(function () {
                    _self.MakeRequest(ctx);
                }, 'sp.js');

            }

        };

        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(CustomEvent);
    };

    this.closest = function (el, tag) {
        tag = tag.toUpperCase();
        do {
            if (el.nodeName === tag) {
                return el;
            }
        } while (el = el.parentNode);

        return null;
    };
    this.LoadingMaskTemplate = function (ctx) {
        return "<div id=\"LoadingMask_" + ctx.wpq + "\"><img src=\"/_layouts/15/images/progress-circle-24.gif?rev=38\" alt=\"Loading...\"></div>";
    };
    this.Mask = function (ctx, Hero) {
        var Hero = Hero || document.getElementById('Hero-' + ctx.wpq);

        var Empty = document.getElementById('empty-' + ctx.wpq);
        if (Empty)
            Empty.setAttribute('class', 'display-none');

        var parentTd = Hero.parentNode;
        if (parentTd)
            parentTd.setAttribute('class', 'display-none');
        var parentTr = _self.closest(parentTd, "tr");
        if (parentTr) {
            var MaskElem = document.createElement("td");
            MaskElem.innerHTML = _self.LoadingMaskTemplate(ctx);
            parentTr.appendChild(MaskElem);
        }
    };
    this.Unmask = function (ctx, Hero) {
        var Hero = Hero || document.getElementById('Hero-' + ctx.wpq);

        var parentTd = Hero.parentNode;
        if (parentTd)
            parentTd.className = parentTd.className.replace('display-none');

        var MaskDiv = document.getElementById('LoadingMask_' + ctx.wpq);
        if (MaskDiv) {
            var td = MaskDiv.parentNode;
            if (td) {
                var tr = td.parentNode;
                if (tr) {
                    tr.removeChild(td);
                }
            }
        }

    };
    this.ResourcedValue = function (value) {
        var returnValue = value;
        if (CIBResources) {
            var resource = CIBResources[_spPageContextInfo.currentCultureName.toLowerCase()];
            if (!resource) {
                resource = CIBResources;
            };
            if (resource) {
                returnValue = resource[value];
            }
        };
        return returnValue;
    };
    this.CreateHeroLink = function (ctx) {
        var Hero = document.getElementById('Hero-' + ctx.wpq);
        if (Hero) {
            var LinkButton = document.getElementById(ctx.heroId);
            if (LinkButton) {
                LinkButton.setAttribute('href', ctx.newFormUrl + "&ContentTypeId=" + _self.CTList[0].id + "&Source=" + encodeURIComponent(window.location.href));
                LinkButton.setAttribute('onclick', 'javascript:;');
                Hero.setAttribute('class', 'display-inlineblock');
            }
        }
    };
    this.CreateCallout = function (ctx) {
        if (_self.CTList.length > 0) {
            var wpq = ctx.wpq;
            var Hero = document.getElementById('Hero-' + wpq);
            if (Hero) {
                var LinkButton = document.getElementById(ctx.heroId);
                EnsureScript('callout.js', typeof CalloutManager, function () {
                    if (!LinkButton) {
                        var links = document.querySelectorAll(".ms-heroCommandLink");
                        if (links.length > 0) {
                            LinkButton = links[0];
                        }
                    }
                    if (LinkButton) {
                        LinkButton.setAttribute('href', 'javascript:;');
                        LinkButton.setAttribute('onclick', 'javascript:;');
                        Hero.setAttribute('class', 'display-inlineblock');

                        if (Boolean(LinkButton)) {
                            var callout = CalloutManager.getFromLaunchPointIfExists(LinkButton);

                            var content = "";
                            var foldersContent = "";
                            for (var i = 0; i < _self.CTList.length; i++) {
                                var CT = _self.CTList[i];
                                var href = ctx.newFormUrl + "&ContentTypeId=" + CT.id + "&Source=" + encodeURIComponent(window.location.href);


                                if (CT.id.indexOf("0x0120") == 0) {
                                    foldersContent += String.format("<a class=\"ms-newdoc-callout-item ms-displayBlock\" onclick=\"CalloutManager.closeAll(); OpenLink('{2}'); return false;\" href=\"javascript:;\"><img src=\"/_layouts/15/images/mb_folder.png?rev=38\" class=\"ms-verticalAlignMiddle ms-newdoc-callout-img\"><h3 class=\"ms-displayInline ms-newdoc-callout-text ms-verticalAlignMiddle ms-soften\">{1}</h3></a>",
                                        wpq, CT.name, href);
                                } else {
                                    content += String.format("<a class=\"ms-newdoc-callout-item ms-displayBlock\" onclick=\"CalloutManager.closeAll(); OpenLink('{2}'); return false;\" href=\"javascript:;\"><img src=\"/_layouts/15/images/256_ICGEN.png?rev=38\" height=\"32px\" class=\"ms-verticalAlignMiddle ms-newdoc-callout-img\"><h3 class=\"ms-displayInline ms-newdoc-callout-text ms-verticalAlignMiddle ms-soften\">{1}</h3></a>",
                                        wpq, CT.name, href);
                                }

                            };

                            var resultContent = "<div id=\"js-newdocWOPI-divMain-WPQ2\" class=\"ms-newdoc-callout-main\" style=\"margin-left: 20px; margin-right: 20px;\">";
                            resultContent += content;
                            if (content && foldersContent) {
                                resultContent += "<hr />";
                            }
                            resultContent += foldersContent;
                            resultContent += "</div>";


                            var calloutOptions = new CalloutOptions();
                            calloutOptions.ID = 'notificationcallout';
                            calloutOptions.launchPoint = LinkButton;
                            calloutOptions.beakOrientation = 'leftRight';
                            calloutOptions.content = resultContent;
                            calloutOptions.title = _self.ResourcedValue('CalloutText');
                            var callout = CalloutManager.createNewIfNecessary(calloutOptions);
                        }

                    }
                });
            }
        }
    };
    this.MakeRequest = function (ctx) {
        var UpdateFolderCT = false;
        if (InParams.UpdateFolderCT && InParams.ContentTypes) {
            UpdateFolderCT = true;
        }

        JSRequest.EnsureSetup();
        var RootFolderUrl = JSRequest.QueryString["RootFolder"];

        var clientContext = new SP.ClientContext();
        var web = clientContext.get_web();

        var targetList = clientContext.get_web().get_lists().getById(_self.listId);

        var contenttypes = targetList.get_contentTypes();

        var folder = targetList.get_rootFolder();
        var folderItem;
        if (RootFolderUrl) {
            folder = web.getFolderByServerRelativeUrl(RootFolderUrl);
            folderItem = folder.get_listItemAllFields();
            clientContext.load(folderItem, 'ContentType');
        } else {
            folderItem = targetList;
        }

        clientContext.load(folder);
        clientContext.load(folder, 'ContentTypeOrder');
        clientContext.load(folderItem, 'EffectiveBasePermissions');
        clientContext.load(targetList);
        clientContext.load(contenttypes);

        clientContext.executeQueryAsync(
			function (data) {
			    var returndata = [];
			    var permission = folderItem.get_effectiveBasePermissions();
			    if (permission.has(SP.PermissionKind.addListItems)) {

			        var contents = folder.get_contentTypeOrder();

			        var CurrentFolderCTId = RootFolderCTId;
			        if (folderItem instanceof SP.ListItem) {
			            CurrentFolderCTId = folderItem.get_contentType().get_id().get_stringValue();
			        }

			        var SelectedCT = [];

			        if (InParams.ContentTypes) {
			            for (var DefaultForCT in InParams.ContentTypes) {
			                if (CurrentFolderCTId.indexOf(DefaultForCT) != -1) {
			                    SelectedCT = InParams.ContentTypes[DefaultForCT];
			                }
			            }
			        };


			        var FolderCTString = "";
			        for (var i = 0; i < contents.length; i++) {
			            var selectedFolderCT = contents[i];
			            FolderCTString += selectedFolderCT.get_stringValue() + ";";
			        }
			        var NewFolderCTString = "";

			        var UpdateFolder = false;
			        var ctEnum = contenttypes.getEnumerator();
			        var NewCTOrderFolder = "";
			        var NewCTOrder = [];

			        while (ctEnum.moveNext()) {
			            var currentCT = ctEnum.get_current();
			            var stringCTId = currentCT.get_id().get_stringValue();

			            if (!currentCT.get_sealed()) {

			                if (SelectedCT.length > 0) {

			                    for (var j = 0; j < SelectedCT.length; j++) {
			                        var AvalCTId = SelectedCT[j];


			                        if (stringCTId.indexOf(AvalCTId) != -1) {

			                            if (NewCTOrderFolder.indexOf(stringCTId + ";") == -1) {
			                                NewCTOrderFolder += stringCTId + ";";

			                                var returnCT = {};
			                                returnCT.name = currentCT.get_name();
			                                returnCT.id = currentCT.get_stringId();
			                                returndata.push(returnCT);

			                                NewCTOrder.push(currentCT.get_id());
			                            }
			                        }
			                    }
			                } else {
			                    if (FolderCTString.indexOf(stringCTId) != -1) {
			                        var returnCT = {};
			                        returnCT.name = currentCT.get_name();
			                        returnCT.id = currentCT.get_stringId();
			                        returndata.push(returnCT);
			                    }
			                }
			            }

			        }

			    }


			    _self.CTList = returndata;

			    if (InParams.HideIfOne && (_self.CTList.length == 1)) {
			        _self.CreateHeroLink(ctx);
			    } else {
			        _self.CreateCallout(ctx);
			    }


			    if (UpdateFolderCT) {
			        if (FolderCTString != NewCTOrderFolder) {
			            folder.set_uniqueContentTypeOrder(NewCTOrder);
			            folder.update();

			            clientContext.executeQueryAsync(function (data) {
			                if (InParams.ReloadPage) {
			                    window.location.href = window.location.href;
			                } else {
			                    if (InParams.Mask) {
			                        _self.Unmask(ctx);
			                    }
			                }

			            }, clientContextError);

			        } else {
			            if (InParams.ReloadPage || InParams.Mask) {
			                _self.Unmask(ctx);
			            }
			        }
			    } else {
			        _self.Unmask(ctx);
			    }

			},
			clientContextError
		);
    };
    function clientContextError(sender, args) {
        console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    function AddStyles() {
        var css = '.display-none{display:none;}.display-inlineblock{display:inline-block;}',
		    head = document.head || document.getElementsByTagName('head')[0],
		    style = document.createElement('style');

        style.type = 'text/css';
        if (style.styleSheet) {
            style.styleSheet.cssText = css;
        } else {
            style.appendChild(document.createTextNode(css));
        }

        head.appendChild(style);
    };

    _init();
};


function OpenLink(href) {
    window.location.href = href;
}


(function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        var params = { Mask: true }; // can be empty or undefined;
        new NewItemCalloutData(params);
    }, 'clienttemplates.js');
})();



/*
//Can use this params

        var params = {
            UpdateFolderCT: false, // Update current folders avalible content types by the next param ContentTypes
            DParamsFrom:"",
            ReloadPage: true, //Reloads the page if current folder content types were updated. Fixes the problem with avalible buttons in ribbon
            Mask: true, // Make the mask of the grid while implementing the solution
            HideIfOne: false, // No callout if there is only one avalible content type
            ContentTypes: {
                "0x012001": ["0x0120004A9083A4725747E78296A9F1ABB5A9FB1", "0x0120004A9083A4725747E78296A9F1ABB5A9FB", "0x0104002BB5ED3433C04A56A1BD4AA2110E4181"],
                "0x0120004A9083A4725747E78296A9F1ABB5A9FB": ["0x0104002BB5ED3433C04A56A1BD4AA2110E4181"]
            } // The tree of content types and reletive content types in folders
        };

*/